package controllers

import (
	"blog-but/models"
	beego "github.com/beego/beego/v2/server/web"
)

type BlogController struct {
	beego.Controller
}

// 添加
func (c *BlogController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	title := c.GetString("title")
	content := c.GetString("content")
	author := c.GetString("author")
	blog := models.Blog{
		Title:   title,
		Content: content,
		Author:  author,
	}
	models.DB.Create(&blog)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
		"data": blog,
	}
	c.ServeJSON()
	return
}

// 列表
func (c *BlogController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	offset := (page - 1) * size

	query := models.DB.Model(&models.Blog{})

	var count int64
	query.Count(&count)

	var blog []models.Blog
	query.Offset(offset).Limit(size).Find(&blog)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "列表展示成功",
		"data": map[string]interface{}{
			"blog":  blog,
			"count": count,
		},
	}
	c.ServeJSON()
	return
}
